//
//  User.m
//  WhoPaid
//
//  Created by user on 9/19/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "User.h"
#import "SBJsonParser.h"
@implementation User
static User *_instance = nil;  // <-- important 
@synthesize _id, _name, _username, _tab, page, photo, facebookid;
#define SERVER_URL @"http://nghexaydung.com/whopaid/public/"
+(User *)instance
{ 
	// skip everything
	if(_instance) return _instance; 
    
	// Singleton
	@synchronized([User class]) 
	{
		if(!_instance)
		{
			_instance = [[self alloc] init];
            
            //	NSLog(@"Creating global instance!"); <-- You should see this once only in your program
		}
        
		return _instance;
	}
    
	return nil;
}
-(NSString *) loginWS:(NSString *)username  passwd:(NSString *)passwd Name:(NSString*)name
{
    SBJsonParser *parser = [[SBJsonParser alloc] init];
    User *user = [User instance];
    name = [name stringByReplacingOccurrencesOfString:@" "
                                           withString:@"%20"];
    NSString *url = [NSString stringWithFormat:@"%@user/login?username=%@&password=%@&name=%@",SERVER_URL,username, passwd, name];
    NSLog(@"login %@",url);
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
    NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
    NSDictionary *obj = [parser objectWithString:json_string error:nil];
    NSString *status = [obj objectForKey:@"success"];
    if([status intValue] == 1){
        user._id = [[obj objectForKey:@"id"] intValue];
        user._name = [obj objectForKey:@"name"];
        user._email = [obj objectForKey:@"mail_address"];
    }
    return status;
}
-(NSString *) loginFacebook:(NSString *)facebookId  Email:(NSString *)email Name:(NSString*)name
{
    SBJsonParser *parser = [[SBJsonParser alloc] init];
    User *user = [User instance];
    name = [name stringByReplacingOccurrencesOfString:@" "
                                           withString:@"%20"];
    NSString *url = [NSString stringWithFormat:@"%@user/loginfacebook?id=%d&facebookid=%@&email=%@&name=%@",SERVER_URL,user._id, facebookId, email, name];
    NSLog(@"login facebook %@",url);
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
    NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
    NSDictionary *obj = [parser objectWithString:json_string error:nil];
    NSString *status = [obj objectForKey:@"success"];
    if([status intValue] == 1){
        user._id = [[obj objectForKey:@"id"] intValue];
        user._name = name;
        user._email = email;
    }
    return status;
}
-(NSMutableArray *) getMemberByEventWS:(int)event_id
{
    NSMutableArray *listData = [[NSMutableArray alloc] init ];
    Event *event = [Event instance];
    SBJsonParser *parser = [[SBJsonParser alloc] init];
    NSString *url = [NSString stringWithFormat:@"%@/user/getmemberbyevent?event_id=%d",SERVER_URL, event._id];
    NSLog(@" get member by event: %@",url);
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
    NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
    NSArray *results = [parser objectWithString:json_string error:nil];
    for (NSDictionary *obj in results)
    {
        //NSString *objRow = [[NSString stringWithFormat:@"%d#%@#%@#%d#%d", [[obj objectForKey:@"user_id"] intValue], [obj objectForKey:@"name"], [obj objectForKey:@"mail_address"], [[obj objectForKey:@"active"] intValue] , [[obj objectForKey:@"owner_id"] intValue] ] retain];
        //[listData addObject:objRow];
        ParticipateClass *par = [[ParticipateClass alloc] init];
        par.userId = [[obj objectForKey:@"user_id"] intValue];
        par.name = [obj objectForKey:@"name"];
        par.image = [obj objectForKey:@"avatar"];
        par.firstMail = [obj objectForKey:@"mail_address"];
        par.idString = [obj objectForKey:@"facebookid"];
        par.active = [[obj objectForKey:@"active"] intValue];
        par.quantity = 1;
        par.price = 0;
        [listData addObject:par];
        [par release];
    }
    return listData;
}

-(void) addMemberWS:(NSInteger)event_id Name:(NSString *)name Email:(NSString *)email
{
    User *user = [User instance];
    name = [name stringByReplacingOccurrencesOfString:@" "
                                           withString:@"%20"];
    NSString *url = [NSString stringWithFormat:@"%@user/addmember?name=%@&email=%@&event_id=%d&user_id=%d",SERVER_URL,name, email, event_id, user._id];
    NSLog(@"\nAdd Member %@",url);
    //NSString *contents = [NSString stringWithContentsOfURL:[NSURL URLWithString:url]];
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
    [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
}    

-(void)updateMemberWS:(int)member_id Name:(NSString *)name Email:(NSString *)email
{
    User *user = [User instance];
    Event *event = [Event instance];
    name = [name stringByReplacingOccurrencesOfString:@" "
                                           withString:@"%20"];
    NSString *url = [NSString stringWithFormat:@"%@user/addmember?id=%d&name=%@&email=%@&event_id=%d&user_id=%d",SERVER_URL,member_id,name, email, event._id, user._id];
    NSLog(@"\nUpdate Member %@",url);
    //NSString *contents = [NSString stringWithContentsOfURL:[NSURL URLWithString:url]];
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
    [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
}

-(UserClass *) getAccountWS:(int) user_id
{
    SBJsonParser *parser = [[SBJsonParser alloc] init];
    NSString *url = [NSString stringWithFormat:@"%@user/getuserinfo?id=%d",SERVER_URL,user_id];
    NSLog(@"get account info: %@", url);
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
    NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
    NSDictionary *obj = [parser objectWithString:json_string error:nil];
    UserClass *user = [[UserClass alloc] init];
    user.userId = [[obj objectForKey:@"id"] intValue];
    user.facebookid = [obj objectForKey:@"facebookid"];
    user.userName = [obj objectForKey:@"name"];
    user.avatar = [obj objectForKey:@"avatar"];
    user.photo = [obj objectForKey:@"photo"];
    user.userEmail = [obj objectForKey:@"mail_address"];
    user.password = [obj objectForKey:@"password"];
    return user;
}

-(void)updateAccountWS:(NSInteger)member_id Name:(NSString *)name Email:(NSString *)email Password:(NSString *)password  Photo:(NSString *)picture
{
    name = [name stringByReplacingOccurrencesOfString:@" "
                                           withString:@"%20"];
    NSString *url = [NSString stringWithFormat:@"%@user/update?id=%d&name=%@&email=%@&password=%@&photo=%@",SERVER_URL,member_id, name, email, password,picture];
    NSLog(@"update account %@",url);
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
    [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
}

-(void) deleteMemberWS:(NSInteger)member_id eventId:(NSInteger)event_id userId:(NSInteger)user_id
{
    NSString *url = [NSString stringWithFormat:@"%@user/delete?id=%d&event_id=%d&user_id=%d",SERVER_URL,member_id, event_id, user_id];
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
    [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
}
-(NSString *) deleteMembers:(NSString *)member_id eventId:(NSInteger)event_id userId:(NSInteger)user_id
{
    SBJsonParser *parser = [[SBJsonParser alloc] init];
    NSString *url = [NSString stringWithFormat:@"%@user/deletes?ids=%@&event_id=%d&user_id=%d",SERVER_URL,member_id, event_id, user_id];
    NSLog(@"delete user %@",url);
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
    NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
    NSDictionary *obj = [parser objectWithString:json_string error:nil];
    return [obj objectForKey:@"success"];
}
-(NSMutableArray *) getRecentUser:(int)user_id
{
    NSMutableArray *listData = [[NSMutableArray alloc] init ];
    SBJsonParser *parser = [[SBJsonParser alloc] init];
    NSString *url = [NSString stringWithFormat:@"%@/user/getrecentuser?user_id=%d",SERVER_URL, user_id];
    NSLog(@" get recent member: %@",url);
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
    NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
    NSArray *results = [parser objectWithString:json_string error:nil];
    for (NSDictionary *obj in results)
    {
        ParticipateClass *par = [[ParticipateClass alloc] init];
        par.userId = [[obj objectForKey:@"user_id"] intValue];
        par.name = [obj objectForKey:@"name"];
        par.image = [obj objectForKey:@"avatar"];
        par.firstMail = [obj objectForKey:@"mail_address"];
        par.idString = [obj objectForKey:@"facebookid"];
        par.quantity = 0;
        par.price = 0;
        par.isUsed = YES;
        //par.firstMail = @"";
        [listData addObject:par];
        [par release];
    }
    return listData;
}

-(void) sendEmailServer:(NSString *)from listEmail:(NSMutableString *) listemail
{
    NSString *url = [NSString stringWithFormat:@"%@user/sendemailface?from=%@&to=%@",SERVER_URL,from, listemail];
    NSLog(@"send emai server %@",url);
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
    [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
}
@end
